package com.koala.auth.config;

import com.koala.common.security.component.KoalaWebResponseExceptionTranslator;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 认证服务器
 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


	private final AuthenticationManager authenticationManager;
	private  final RedisConnectionFactory redisConnectionFactory;
	private final UserDetailsService userDetailsService;
	//private final KoalaWebResponseExceptionTranslator koalaWebResponseExceptionTranslator;

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security)
			throws Exception {
		security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
				.allowFormAuthenticationForClients();
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints)
			throws Exception {
		endpoints.tokenStore(tokenStore())
				.userDetailsService(userDetailsService)
				.authenticationManager(authenticationManager)
				.exceptionTranslator(new KoalaWebResponseExceptionTranslator());

	}

	@Bean
	public TokenStore tokenStore(){
		RedisTokenStore tokenStore=new RedisTokenStore(redisConnectionFactory);
		tokenStore.setPrefix("koala_");
		return tokenStore;
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory().withClient("client").secret("{noop}secret")
				.accessTokenValiditySeconds(52000)
				.authorizedGrantTypes("refresh_token", "password").scopes("all");
	}

}
